package com.rose.springbootgeneratefile.codegen;

import com.rose.springbootgeneratefile.api.PropertyRegistry;
import com.rose.springbootgeneratefile.api.dom.java.*;
import com.rose.springbootgeneratefile.internal.utils.JavaBeansUtil;

import java.util.List;
import java.util.Properties;

public abstract class AbstractJavaGenerator extends AbstractGenerator  {

    public abstract List<CompilationUnit> getCompilationUnits();

    /**
     * 生成get方法
     * @param field
     * @return
     */
    public static Method getGetter(Field field) {
        Method method = new Method();
        method.setName(JavaBeansUtil.getGetterMethodName(field.getName(), field
                .getType()));
        method.setReturnType(field.getType());
        method.setVisibility(JavaVisibility.PUBLIC);
        StringBuilder sb = new StringBuilder();
        sb.append("return "); //$NON-NLS-1$
        sb.append(field.getName());
        sb.append(';');
        method.addBodyLine(sb.toString());
        return method;
    }

    /**
     * 获取根class
     * @return
     */
    public String getRootClass() {
        String rootClass = introspectedTable
                .getTableConfigurationProperty(PropertyRegistry.ANY_ROOT_CLASS);
        if (rootClass == null) {
            Properties properties = context
                    .getJavaModelGeneratorConfiguration().getProperties();
            rootClass = properties.getProperty(PropertyRegistry.ANY_ROOT_CLASS);
        }

        return rootClass;
    }

    /**
     * 生成默认构造方法
     * @param topLevelClass
     */
    protected void addDefaultConstructor(TopLevelClass topLevelClass) {
        Method method = new Method();
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setConstructor(true);
        method.setName(topLevelClass.getType().getShortName());
        method.addBodyLine("super();"); //$NON-NLS-1$
        context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
        topLevelClass.addMethod(method);
    }
}
